package com.explment.lens.utils.snowid;

import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 雪花生成id
 * 每个节点的datacenterId和workerId必须全局唯一
 * 系统时钟不能频繁回拨
 * 序列号用尽时会等待到下一毫秒继续生成
 */
public class SnowflakeIdGeneratorID{
    // 基础配置参数
    private static final long EPOCH = 1609459200000L; // 2021-01-01 00:00:00
    private static final long WORKER_ID_BITS = 5L;
    private static final long DATACENTER_ID_BITS = 5L;
    private static final long SEQUENCE_BITS = 12L;

    // 最大取值范围
    private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
    private static final long MAX_DATACENTER_ID = ~(-1L << DATACENTER_ID_BITS);
    private static final long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS);

    // 位移偏移量
    private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;
    private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
    private static final long TIMESTAMP_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;

    // 实例状态
    private final long workerId;
    private final long datacenterId;
    private long sequence = 0L;
    private volatile long lastTimestamp = -1L;
    private final AtomicLong clockDriftCounter = new AtomicLong(0);
    private final Lock lock = new ReentrantLock();

    // 监控指标
    private volatile long lastGeneratedId;
    private final AtomicLong totalGenerated = new AtomicLong(0);

    public SnowflakeIdGeneratorID(long workerId, long datacenterId) {
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException("Worker ID超出范围");
        }
        if (datacenterId > MAX_DATACENTER_ID || datacenterId < 0) {
            throw new IllegalArgumentException("Datacenter ID超出范围");
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    public long nextId() {
        lock.lock();
        try {
            long timestamp = timeGen();

            // 时钟回拨处理
            if (timestamp < lastTimestamp) {
                long offset = lastTimestamp - timestamp;
                if (offset <= 5) {
                    timestamp = waitUntilNextMillis();
                } else if (offset <= 1000) {
                    clockDriftCounter.incrementAndGet();
                    timestamp = lastTimestamp + 1;
                } else {
                    throw new RuntimeException(String.format(
                            "时钟回拨超过阈值 %dms，最后记录时间：%d，当前时间：%d",
                            offset, lastTimestamp, timestamp));
                }
            }

            // 同一毫秒内序列号递增
            if (timestamp == lastTimestamp) {
                sequence = (sequence + 1) & SEQUENCE_MASK;
                if (sequence == 0) {
                    timestamp = waitUntilNextMillis();
                }
            } else {
                sequence = 0L;
            }

            lastTimestamp = timestamp;
            long id = ((timestamp - EPOCH) << TIMESTAMP_SHIFT)
                    | (datacenterId << DATACENTER_ID_SHIFT)
                    | (workerId << WORKER_ID_SHIFT)
                    | sequence;

            // 更新监控数据
            lastGeneratedId = id;
            totalGenerated.incrementAndGet();
            return id;
        } finally {
            lock.unlock();
        }
    }

    private long waitUntilNextMillis() {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            Thread.yield();
            timestamp = timeGen();
        }
        return timestamp;
    }

    private long timeGen() {
        return System.currentTimeMillis();
    }

    // 监控接口
    public long getClockDriftCount() {
        return clockDriftCounter.get();
    }

    public long getTotalGenerated() {
        return totalGenerated.get();
    }

    public String getLastIdInfo() {
        return String.format("ID: %d (Timestamp: %d, Worker: %d, DC: %d, Seq: %d)",
                lastGeneratedId,
                (lastGeneratedId >> TIMESTAMP_SHIFT) + EPOCH,
                (lastGeneratedId >> WORKER_ID_SHIFT) & MAX_WORKER_ID,
                (lastGeneratedId >> DATACENTER_ID_SHIFT) & MAX_DATACENTER_ID,
                lastGeneratedId & SEQUENCE_MASK);
    }

//    public static void main(String[] args) {
//        SnowflakeIdGeneratorID generator = new SnowflakeIdGeneratorID(1, 1);
//        for (int i = 0; i < 10; i++) {
//            System.out.println(generator.nextId());
//        }
//    }
}
